import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:html_editor_mobile/html_editor.dart';

void main() => runApp(HtmlEditorExampleApp());

class HtmlEditorExampleApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(),
      darkTheme: ThemeData.dark(),
      home: HtmlEditorExample(title: 'Flutter HTML Editor Example'),
    );
  }
}

class HtmlEditorExample extends StatefulWidget {
  HtmlEditorExample({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _HtmlEditorExampleState createState() => _HtmlEditorExampleState();
}

class _HtmlEditorExampleState extends State<HtmlEditorExample> {
  String result = '';
  final HtmlEditorController controller = HtmlEditorController();
  bool isBoldActive = false;
  bool isUnorderedListActive = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 注册状态更新回调
    controller.onToolbarStatusChanged = (Map<String, bool> status) {
      setState(() {
        isBoldActive = status['bold'] ?? false;
        isUnorderedListActive = status['unorderedList'] ?? false;
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    double screenHeight = MediaQuery.of(context).size.height;
    double appBarHeight = kToolbarHeight; // AppBar 默认高度
    double fabHeight = kBottomNavigationBarHeight; // FloatingActionButton 可能占的高度
    double safeAreaPadding =
        MediaQuery.of(context).padding.top + MediaQuery.of(context).padding.bottom;
    double editorHeight = screenHeight - appBarHeight - safeAreaPadding; // 预留 20px 额外空间

    final bottomInset = MediaQuery.of(context).viewInsets.bottom;
    final isKeyboardVisible = bottomInset > 100.0;

    return GestureDetector(
      onTap: () {
        if (!kIsWeb) {
          controller.clearFocus();
        }
      },
      child: Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          title: Text(widget.title),
          elevation: 0,
          actions: [
            IconButton(
                icon: Icon(Icons.refresh),
                onPressed: () {
                  if (kIsWeb) {
                    controller.reloadWeb();
                  } else {
                    controller.editorController!.reload();
                  }
                })
          ],
        ),
        body: SafeArea(
            child: Column(
          children: [
            /*SingleChildScrollView(
              child: ,
            )*/
            Expanded(
                child: SingleChildScrollView(
                    child: HtmlEditor(
              controller: controller,
              htmlEditorOptions: HtmlEditorOptions(
                shouldEnsureVisible: true,
                hint: "输入内容",
                // initialText: "初始化数据",
              ),
              htmlToolbarOptions: HtmlToolbarOptions(
                toolbarPosition: ToolbarPosition.custom,
                //by default
                toolbarType: ToolbarType.nativeScrollable,
                //by default
                onButtonPressed: (ButtonType type, bool? status, Function? updateStatus) {
                  print(
                      "button '${describeEnum(type)}' pressed, the current selected status is $status");
                  return true;
                },
                onDropdownChanged:
                    (DropdownType type, dynamic changed, Function(dynamic)? updateSelectedItem) {
                  print("dropdown '${describeEnum(type)}' changed to $changed");
                  return true;
                },
                mediaLinkInsertInterceptor: (String url, InsertFileType type) {
                  print(url);
                  return true;
                },
                mediaUploadInterceptor: (PlatformFile file, InsertFileType type) async {
                  print(file.name); //filename
                  print(file.size); //size in bytes
                  print(file.extension); //file extension (eg jpeg or mp4)
                  return true;
                },
              ),
              otherOptions: OtherOptions(height: editorHeight),
              callbacks: Callbacks(onBeforeCommand: (String? currentHtml) {
                print('html before change is $currentHtml');
              }, onChangeContent: (String? changed) {
                print('content changed to $changed');
              }, onChangeCodeview: (String? changed) {
                print('code changed to $changed');
              }, onChangeSelection: (EditorSettings settings) {
                print('parent element is ${settings.parentElement}');
                print('font name is ${settings.fontName}');
              }, onDialogShown: () {
                print('dialog shown');
              }, onEnter: () {
                print('enter/return pressed');
              }, onFocus: () {
                print('editor focused');
              }, onBlur: () {
                print('editor unfocused');
              }, onBlurCodeview: () {
                print('codeview either focused or unfocused');
              }, onInit: () {
                // controller.setFontSize(30);
                controller.setText("初始化数据");
                // print('------------初始化-init-----');
              },
                  //this is commented because it overrides the default Summernote handlers
                  /*onImageLinkInsert: (String? url) {
                    print(url ?? "unknown url");
                  },
                  onImageUpload: (FileUpload file) async {
                    print(file.name);
                    print(file.size);
                    print(file.type);
                    print(file.base64);
                  },*/
                  onImageUploadError: (FileUpload? file, String? base64Str, UploadError error) {
                print(describeEnum(error));
                print(base64Str ?? '');
                if (file != null) {
                  print(file.name);
                  print(file.size);
                  print(file.type);
                }
              }, onKeyDown: (int? keyCode) {
                print('$keyCode key downed');
                print('current character count: ${controller.characterCount}');
              }, onKeyUp: (int? keyCode) {
                print('$keyCode key released');
              }, onMouseDown: () {
                print('mouse downed');
              }, onMouseUp: () {
                print('mouse released');
              }, onNavigationRequestMobile: (String url) {
                print(url);
                return NavigationActionPolicy.ALLOW;
              }, onPaste: () {
                print('pasted into editor');
              }, onScroll: () {
                print('editor scrolled');
              }),
              /*   plugins: [
                  SummernoteAtMention(
                      getSuggestionsMobile: (String value) {
                        var mentions = <String>['test1', 'test2', 'test3'];
                        return mentions.where((element) => element.contains(value)).toList();
                      },
                      mentionsWeb: ['test1', 'test2', 'test3'],
                      onSelect: (String value) {
                        print(value);
                      }),
                ],*/
            ))),
            // KeyboardVisibilityBuilder(builder: (BuildContext , bool isKeyboardVisible) {  },),
            // 键盘可见性检测
            Visibility(
                visible: isKeyboardVisible,
                child: Container(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: 8),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.format_bold,
                            color: isBoldActive ? Colors.blue : Colors.black),
                        onPressed: () {
                          controller.execCommand('bold');
                          setState(() {
                            isBoldActive = !isBoldActive;
                          });
                        },
                      ),
                      IconButton(
                        icon: Icon(Icons.format_list_bulleted,
                            color: isUnorderedListActive ? Colors.blue : Colors.black),
                        onPressed: () {
                          controller.execCommand('insertUnorderedList');
                          setState(() {
                            isUnorderedListActive = !isUnorderedListActive;
                          });
                        },
                      ),
                      IconButton(
                        icon: Icon(
                          Icons.font_download,
                        ),
                        onPressed: () {
                          controller.setFontSize(18);
                          setState(() {});
                        },
                      ),
                    ],
                  ),
                ))
          ],
        )),
      ),
    );
  }
}
